# -*- coding: utf-8 -*-
import akshare as ak
import pandas as pd
from loguru import logger
from typing import Optional
from config.settings import settings
from services.commons import run_with_timeout

class FuturesHistoryService:
    """
    获取期货历史数据的服务
    """

    def get_history_data(self, symbol: str, period: str = "1d") -> Optional[pd.DataFrame]:
        """
        获取指定期货合约的分钟线或日线历史数据

        Args:
            symbol (str): 期货合约代码, e.g., "IM2512"
            period (str): 数据周期, "1m" for 1-minute, "5m" for 5-minute, "1d" for daily.

        Returns:
            Optional[pd.DataFrame]: 包含历史数据的DataFrame, 失败则返回None
        """
        try:
            timeout = settings.request_timeout_seconds
            if period in ["1m", "5m", "15m", "30m", "60m"]:
                df = run_with_timeout(
                    ak.futures_zh_minute_sina, timeout, symbol=symbol, period=period
                )
            elif period == "1d":
                df = run_with_timeout(
                    ak.futures_zh_daily_sina, timeout, symbol=symbol
                )
            else:
                logger.error(f"Unsupported period: {period}")
                return None
            
            # The sample ohlcv.csv has columns: date, open, high, low, close, volume
            # ak.futures_zh_minute_sina returns: date, open, high, low, close, volume, hold
            # ak.futures_zh_daily_sina returns: date, open, high, low, close, volume, hold, settlement
            # Let's make them consistent.
            if 'date' not in df.columns:
                df.rename(columns={'datetime': 'date'}, inplace=True)

            return df[['date', 'open', 'high', 'low', 'close', 'volume']]

        except Exception as e:
            logger.error(f"Failed to get history data for {symbol} with period {period}: {e}")
            return None
